import './SignUpLoading.scss'
import { v4 } from 'uuid'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useMount } from 'ahooks'
import { useRequest } from 'alova/client'
import { App, Result, Button } from "antd"

import { API_LIST } from '../../Utils/Api'
import { WeChatConfig } from '../../Config/theme'

import { getSignUpBack } from '../../Utils'
import { modelStore, drawerStore, fromStore } from '../../Config/zustand'

const { appid, redirect_uri } = WeChatConfig

const SignScanCode = ({ Off }) => {

    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const { updateFromData } = fromStore()

    const [uuid] = useState(v4())

    const onNavigate = useNavigate()

    const [loading, setLoading] = useState(false)
    const onAdmin = () => onNavigate('/Admin')
    const onStart = () => onNavigate('/Start/Home')

    useEffect(() => {
        updateModel({})
        updateDrawer({})
        updateFromData({})
        const state = `${uuid}@${appid}@jiantou@true`
        const get = `${API_LIST()['getCommonGetOpenUnionidOrTokenSSE']}?QRUuid=${uuid}&Type=token`
        const codeData = {
            self_redirect: true,
            id: 'QRcode',
            appid,
            scope: 'snsapi_login',
            response_type: 'code',
            redirect_uri: window.encodeURI(redirect_uri),
            state: state,
            style: 'black',
            href: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/code.css',
        }

        var eventSource = new EventSource(get)
        eventSource.onopen = () => new window.WxLogin(codeData)
        eventSource.onmessage = e => {
            const { data } = e
            if (data !== '0') onSignUp(data)
        }
        eventSource.onerror = () => eventSource.close()
        return () => {
            eventSource.close()
        }
    }, [uuid])

    const onSignUp = async (data) => {
        try {
            const params = await getSignUpBack(data)
            if (!params) {
                return Off()
            }
            if (params.find(v => v.uuid === '00000000-0000-0000-0000-000000000001')) {
                return setLoading(true)
            } else {
                return onAdmin()
            }
        } catch (err) { Off() }
    }

    return (
        <div className='SignUpLoading'>
            {loading &&
                <div className="onSign">
                    <Button type="primary" size="large" onClick={onAdmin}>后台</Button>
                    <Button size="large" onClick={onStart}>大屏</Button>
                </div>
            }
            {!loading && <div id="QRcode" />}
        </div>
    );
};

export default SignScanCode;